// 作文上传页面逻辑
const essayApi = require('../../api/essayApi');
const app = getApp();

Page({
  data: {
    points: 0,
    tempFilePath: '',
    submitting: false
  },

  onLoad: function (options) {
    // 页面初始化
  },
  
  onShow: function () {
    // 每次显示页面时更新积分
    this.setData({
      points: app.globalData.points || 0
    });
  },
  
  // 选择图片
  chooseImage: function () {
    const that = this;
    
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          tempFilePath: res.tempFilePaths[0]
        });
      }
    });
  },
  
  // 提交作文进行批改
  submitEssay: function () {
    if (this.data.submitting) return;
    
    const that = this;
    const { tempFilePath, points } = this.data;
    
    // 检查是否有足够的积分
    if (points <= 0) {
      wx.showModal({
        title: '积分不足',
        content: '您的积分不足，无法进行批改，是否前往充值？',
        confirmText: '去充值',
        success: function (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/recharge/recharge'
            });
          }
        }
      });
      return;
    }
    
    // 检查是否已选择图片
    if (!tempFilePath) {
      wx.showToast({
        title: '请先选择作文图片',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ submitting: true });
    
    // 上传图片
    essayApi.uploadEssay(tempFilePath)
      .then(result => {
        // 批改作文
        return essayApi.correctEssay(result.essayId);
      })
      .then(result => {
        // 更新积分
        app.globalData.points = result.points;
        
        // 跳转到批改结果页面
        wx.navigateTo({
          url: `/pages/correction/correction?id=${result.essayId}`
        });
      })
      .catch(err => {
        console.error('提交作文失败', err);
        wx.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ submitting: false });
      });
  }
}); 